/**
 * 1.promise 就是一个类 要有执行器  并立即执行
 * 2. 三种状态 成功 fulfilled 失败rejected 等待pendding
 *   状态更改 就不会变了 默认是pendding
 * 3.resolve 和reject是修改状态的
 * 4.then方法判断状态 并调用各状态的回调函数
 * 5. then 回调有值 成功 或 失败 
 * 6.同一个promise对象下面的then方法是可以被调用多次的
 * 7.then方法链式调用，后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
 */

const FULFILLED = 'fulfilled' //成功
const REJECTED = 'rejected' //失败
const PENDING = 'pending' // 等待

class MyPromise {

  constructor(executor) {

    try {
      executor(this.resolve, this.reject)
    } catch (error) {
      this.reject(error)
    }
  }
  // promise状态
  status = PENDING;
  // 成功值
  value = undefined;
  // 失败值
  reason = undefined;
  // 成功回调
  sucessCallback = [];
  // 失败回调
  failCallback = [];
  resolve = value => {
    // 判断状态改变了return
    if (this.status !== PENDING) return;
    //更改状态-成功
    this.status = FULFILLED;
    // 保存成功的值
    this.value = value
    // 判断成功回调是否存在 如果在 》调用
    // this.sucessCallback && this.sucessCallback(this.value)
    while (this.sucessCallback.length) this.sucessCallback.shift()()
  }
  reject = reason => {
    // 判断状态改变了return
    if (this.status !== PENDING) return;
    //更改状态-失败
    this.status = REJECTED;
    // 保存失败的值
    this.reason = reason;
    // 判断失败回调是否存在 如果在 》调用
    // this.failCallback && this.failCallback(this.reason)
    while (this.failCallback.length) this.failCallback.shift()()
  }
  // then 方法
  then(sucessCallback, failCallback) {
    // then().then() 空值判断
    sucessCallback = sucessCallback ? sucessCallback : value => value;
    // then().then() 空值判断
    failCallback = failCallback ? failCallback : reason => { throw reason };
    let promise2 = new MyPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        // 使其异步
        setTimeout(() => {
          try {
            let x = sucessCallback(this.value);
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0);

      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallback(this.reason);
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0);
      } else {
        // 等到
        // 存储成功和失败的回调
        this.sucessCallback.push(() => {
          setTimeout(() => {
            try {
              let x = sucessCallback(this.value);
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0);
        });
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason);
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0);
        });
      }
    })

    return promise2
  }
  finally(callback) {
    return this.then(value => {
      return MyPromise.resolve(callback()).then(() => value)
    }, reason => {
      return MyPromise.resolve(callback()).then(() => { throw reason })
    })
  }
  catch(failCallback) {
    return this.then(undefined, failCallback)
  }
  static all(array) {
    let result = [];
    let index = 0;

    return new MyPromise((resolve, reject) => {
      function addData(key, value) {
        result[key] = value
        index++;
        if (index === array.length) {
          resolve(result)
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i]
        if (current instanceof MyPromise) {
          // promise
          current.then(value => addData(i, value), reason => reject(reason))
        } else {
          // 普通值
          addData(i, array[i])
        }
      }

    })
  }
  static resolve(value) {
    if (value instanceof MyPromise) {
      return value
    } else {
      return new MyPromise(resolve => resolve(value))
    }
  }
}
function resolvePromise(promise2, x, resolve, reject) {
  if (promise2 === x) return reject(new TypeError('报错了'))
  if (x instanceof MyPromise) {
    x.then(resolve, reject)
  } else {
    // 普通值
    resolve(x)
  }
}


module.exports = MyPromise;